/*
 * @Author: 徐建辰
 * @Date: 2022-04-16 12:47:15
 * @LastEditTime: 2022-04-16 12:49:57
 * @LastEditors: 徐建辰
 * @Description: 工具函数集合
 */
// 全屏操作
export const fullscreen = element => {
  if (!element) return
  const documentObj = document
  const isFull = !!(documentObj.webkitIsFullScreen || documentObj.mozFullScreen || documentObj.msFullscreenElement || documentObj.fullscreenElement)
  if (isFull) {
		if (documentObj.exitFullscreen) {
			documentObj.exitFullscreen()
		} else if (documentObj.msExitFullscreen) {
			documentObj.msExitFullscreen()
		} else if (documentObj.mozCancelFullScreen) {
			documentObj.mozCancelFullScreen()
		} else if (documentObj.webkitExitFullscreen) {
			documentObj.webkitExitFullscreen()
		}
	} else {
		if (element.requestFullscreen) {
			element.requestFullscreen()
		} else if (element.msRequestFullscreen) {
			element.msRequestFullscreen()
		} else if (element.mozRequestFullScreen) {
			element.mozRequestFullScreen()
		} else if (element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen()
		}
	}
}

export const asyncLoadScript = (src, existVariable, callback) => {
  // 是否已经存在
  const existingScript = document.getElementById(src)
  const cb = callback || function() {}
  // 如果没存在创建相应element
  if (!existingScript) {
    const script = document.createElement('script')
    script.src = src
    script.id = src
    document.body.appendChild(script)
    const onEnd = 'onload' in script ? stdOnEnd : ieOnEnd
    onEnd(script)
  }
  if (existingScript && callback) {
    existVariable && cb(null, existingScript)
  }
  // 等待加载完成
  function stdOnEnd(script) {
    script.onload = function() {
      this.onerror = this.onload = null
      cb(null, script)
    }
    //错误回调
    script.onerror = function() {
      this.onerror = this.onload = null
      cb(new Error('Failed to load ' + src), script)
    }
  }
  // 针对ie浏览器进行处理
  function ieOnEnd(script) {
    script.onreadystatechange = function() {
      if (this.readyState !== 'complete' && this.readyState !== 'loaded') return
      this.onreadystatechange = null
      cb(null, script)
    }
  }
}